import {
  addPlatApply,
  delPlatApply,
  getPlatApplyList,
  upPlatApply
} from "@/api/other/platApply";
import { getUserList } from "@/api/system/user";
import { addDialog } from "@/components/ReDialog";
import { useUserStoreHook } from "@/store/modules/user";
import { exportData, formatDate, getTableCol } from "@/utils/common";
import { message } from "@/utils/message";
import {
  checkStatusRend,
  dataStatusRend,
  rejectDescRend,
  tableFileRend
} from "@/utils/table";
import type { PaginationProps } from "@pureadmin/table";
import { deviceDetection, getKeyList } from "@pureadmin/utils";
import dayjs from "dayjs";
import { type Ref, computed, h, onMounted, reactive, ref } from "vue";
import { useRoute } from "vue-router";
import editForm from "../form/index.vue";
import showDetail from "../form/showDetail.vue";

export function useUser(tableRef: Ref) {
  const form = reactive({
    writeObjective: "",
    finalResult: "",
    examineStatus: "",
    status: "",
    orderBy: "desc",
    pageNum: 1,
    pageSize: 10
  });
  const formRef = ref();
  const dataList = ref([]);
  const allUserList = ref([]);
  const loading = ref(true);
  const tableCol = ref<any>({});
  const treeData = ref([]);
  const selectedNum = ref(0);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "平台名称",
      prop: "finalResult",
      fixed: "left",
      minWidth: 200
    },
    {
      label: "审核状态",
      prop: "examineStatus",
      minWidth: 90,
      cellRenderer: checkStatusRend
    },
    {
      label: "状态",
      prop: "status",
      minWidth: 80,
      cellRenderer: dataStatusRend
    },
    {
      label: "驳回原因",
      prop: "examineDesc",
      minWidth: 120,
      cellRenderer: rejectDescRend
    },
    {
      label: "平台级别",
      prop: "writeObjective",
      minWidth: 100
    },
    {
      label: "申报负责人",
      prop: "masterUserName",
      minWidth: 100
    },
    {
      label: "申报参与人",
      prop: "userList",
      minWidth: 120,
      formatter: ({ userList }) => userList.map(v => v.name).join(",")
    },
    {
      label: "申报日期",
      prop: "firstAccountDate",
      minWidth: 110,
      formatter: ({ firstAccountDate }) => formatDate(firstAccountDate)
    },
    {
      label: "获批日期",
      prop: "secondAccountDate",
      minWidth: 110,
      formatter: ({ secondAccountDate }) => formatDate(secondAccountDate)
    },
    {
      label: "通知文件",
      prop: "writeObjectiveFiles",
      minWidth: 100,
      cellRenderer: ({ row }) => tableFileRend(row, "writeObjectiveFiles")
    },
    {
      label: "申报文件",
      prop: "finalResultFiles",
      minWidth: 100,
      cellRenderer: ({ row }) => tableFileRend(row, "finalResultFiles")
    },
    {
      label: "获批文件",
      prop: "finalFiles",
      minWidth: 100,
      cellRenderer: ({ row }) => tableFileRend(row, "finalFiles")
    },
    {
      label: "积分",
      prop: "score",
      minWidth: 100
    },
    {
      label: "创建人",
      prop: "createUserName",
      minWidth: 100
    },
    {
      label: "创建时间",
      prop: "gmtCreate",
      minWidth: 140,
      formatter: ({ gmtCreate }) => dayjs(gmtCreate).format("YYYY-MM-DD HH:mm")
    },
    {
      label: "修改时间",
      prop: "gmtModified",
      minWidth: 140,
      formatter: ({ gmtModified }) =>
        dayjs(gmtModified).format("YYYY-MM-DD HH:mm")
    },
    {
      label: "操作",
      prop: "operation",
      fixed: "right",
      align: "left",
      width: 190,
      slot: "operation"
    }
  ];

  const buttonClass = computed(() => {
    return [
      "!h-[20px]",
      "reset-margin",
      "!text-gray-500",
      "dark:!text-white",
      "dark:hover:!text-primary"
    ];
  });

  const handleDelete = async row => {
    await delPlatApply(row.id);
    message("删除成功", { type: "success" });
    onSearch();
  };

  function handleSizeChange(val: number) {
    console.log(`${val} items per page`);
    form.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    console.log(`current page: ${val}`);
    form.pageNum = val;
    onSearch();
  }

  /** 批量删除 */
  function onbatchDel() {
    // 返回当前选中的行
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    // 接下来根据实际业务，通过选中行的某项数据，比如下面的id，调用接口进行批量删除
    message(`已删除用户编号为 ${getKeyList(curSelected, "id")} 的数据`, {
      type: "success"
    });
    tableRef.value.getTableRef().clearSelection();
    onSearch();
  }

  const loadAllUser = async () => {
    let params = {
      flag: 1,
      pageNum: 1,
      pageSize: 500
    };
    let { data } = await getUserList(params);
    allUserList.value = data.records || [];
  };

  async function onSearch() {
    loading.value = true;
    const { data } = await getPlatApplyList(form);
    dataList.value = data.records || [];
    pagination.total = data.total;
    pagination.pageSize = data.pageSize;
    pagination.currentPage = data.pageNum;

    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  // 导出数据
  const exportModuleData = () => {
    exportData("平台申报", "/platform/declaration/export", form);
  };

  function openDetail(title = "新增", row?) {
    addDialog({
      title: "查看平台申报",
      props: {
        formInline: {
          id: row?.id ?? undefined,
          createUserId: row?.createUserId ?? undefined,
          title,
          finalFiles: row?.finalFiles ?? "",
          finalResult: row?.finalResult ?? "",
          finalResultFiles: row?.finalResultFiles ?? "",
          firstAccountDate: row?.firstAccountDate ?? "",
          secondAccountDate: row?.secondAccountDate ?? "",
          score: row?.score ?? null,
          writeObjective: row?.writeObjective ?? "",
          writeObjectiveFiles: row?.writeObjectiveFiles ?? "",
          shenMasterName: row?.shenMasterName ?? "",
          masterUserName: row?.masterUserName ?? "",
          userList: row?.userList ?? "",
          shenPartName: row?.shenPartName ?? "",
          examineStatus: row?.examineStatus ?? 0,
          examineDesc: row?.examineDesc ?? ""
        },
        userList: row?.userList || []
      },
      width: "600px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(showDetail),
      beforeSure: done => {
        done();
      }
    });
  }

  function openDialog(title = "新增", row?) {
    let userId = useUserStoreHook().id;
    if (userId == 1) {
      userId = null;
    }
    let userIds = [];
    if (row?.userList) {
      userIds = row.userList.map(v => v.id);
    }
    addDialog({
      title: `${title}平台申报`,
      props: {
        formInline: {
          id: row?.id ?? undefined,
          finalFiles: row?.finalFiles ?? "",
          finalResult: row?.finalResult ?? "",
          finalResultFiles: row?.finalResultFiles ?? "",
          score: row?.score ?? null,
          firstAccountDate: formatDate(row?.firstAccountDate, ""),
          secondAccountDate: formatDate(row?.secondAccountDate, ""),
          writeObjective: row?.writeObjective ?? "",
          writeObjectiveFiles: row?.writeObjectiveFiles ?? "",
          shenMasterName: row?.shenMasterName ?? "",
          shenPartName: row?.shenPartName ?? "",
          masterUserId: row?.masterUserId ?? userId,
          userIds: userIds
        },
        userList: allUserList
      },
      width: "600px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline;
        console.log("curData", curData);
        function chores() {
          message("操作成功", { type: "success" });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(async valid => {
          if (valid) {
            console.log("curData ", curData);
            curData.score = curData.score || 0;
            // 表单规则校验通过
            if (title === "新增") {
              await addPlatApply(curData);
              chores();
            } else {
              delete curData.password;
              await upPlatApply(curData);
              chores();
            }
          }
        });
      }
    });
  }

  onMounted(async () => {
    const { query } = useRoute();
    if (query.examineStatus) {
      form.examineStatus = Number(query.examineStatus) as any;
    }
    if (query.status) {
      form.status = Number(query.status) as any;
    }
    tableCol.value = await getTableCol("platApplyHome");

    onSearch();

    // 获取所有用户
    loadAllUser();
  });

  return {
    form,
    tableCol,
    loading,
    columns,
    dataList,
    treeData,
    selectedNum,
    pagination,
    buttonClass,
    deviceDetection,
    onSearch,
    resetForm,
    onbatchDel,
    openDialog,
    openDetail,
    handleDelete,
    handleSizeChange,
    handleCurrentChange,
    exportModuleData
  };
}
